package com.abl.core.service.sys.impl;


import com.abl.core.common.cache.Cache;
import com.abl.core.common.cache.CacheKey;
import com.abl.core.common.util.StringKit;
import com.abl.core.domain.db.SysDict;
import com.abl.core.domain.project.PageSearch;
import com.abl.core.mybatis.mapper.SysDictMapper;
import com.abl.core.service.sys.SysDictService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.abl.core.domain.db.table.SysDictTableDef.SYS_DICT;

/**
 * 字典表实现
 */
@Slf4j
@Service
public class SysDictServiceImpl implements SysDictService {
    @Resource
    private Cache<String> cache;

    @Resource
    private SysDictMapper dictMapper;

    //新增
    @Override
    public boolean insert(SysDict param) {
        //        String dictKey = param.getDictKey();
        //        LogicDeleteManager.execWithoutLogicDelete(() -> {
        //            QueryWrapper wrapper = QueryWrapper.create().where(SYS_DICT.DICT_KEY.eq(dictKey)).and(SYS_DICT.DEL.in("0", "1"));
        //            SysDict sysDict = dictMapper.selectOneByQuery(wrapper);
        //            if (sysDict != null) throw new ServiceException(MSG.KEY_EXISTS);
        dictMapper.insertSelective(param);
        //        });

        //清缓存
        clearCache();
        return true;
    }

    //删除
    @Override
    public boolean delete(String ids) {
        ArrayList<String> split = StringKit.split(ids);
        int i = dictMapper.deleteBatchByIds(split);

        //清缓存
        clearCache();
        return true;
    }

    //修改
    @Override
    public boolean update(SysDict param) {
        dictMapper.update(param);

        //清缓存
        clearCache();
        return true;
    }

    @Override
    public Page<SysDict> page(SysDict param, PageSearch pageSearch) {
        return dictMapper.paginate(pageSearch, searchQueryWrapper(param));
    }

    //查询详情
    @Override
    public JSONObject info(SysDict param) {
        return null;
    }

    //查询集合
    @Override
    public List<SysDict> list(SysDict param) {
        return null;
    }

    //清除缓存
    @Override
    public void clearCache() {
        cache.delete(CacheKey.DICT_ALL_DATA);
    }

    /**
     * 从缓存中获取字典数据
     */
    @Override
    public List<SysDict> allDict() {
        String allDict = cache.getString(CacheKey.DICT_ALL_DATA);

        //查询可用字典加入缓存
        if (StringKit.isBlank(allDict)) {
            List<SysDict> sys_dict = dictMapper.selectListByQuery(QueryWrapper.create().from(SYS_DICT).where(SYS_DICT.STATUS.eq("0")));
            cache.set(CacheKey.DICT_ALL_DATA, JSON.toJSONString(sys_dict));
            return sys_dict;
        }

        return JSON.parseArray(allDict, SysDict.class);
    }

    @Override
    public List<SysDict> allDictEnum(SysDict param) {
        param.setType("1");
        return dictMapper.selectListByQuery(searchQueryWrapper(param));
    }

    private QueryWrapper searchQueryWrapper(SysDict param) {
        String id = param.getId();
        String dictKey = param.getDictKey();
        String dictValue = param.getDictValue();
        String moduleName = param.getModuleName();
        String dictName = param.getDictName();
        String type = param.getType();

        return QueryWrapper.create().
                where(SYS_DICT.ID.like(id)).and(SYS_DICT.DICT_KEY.like(dictKey))
                .and(SYS_DICT.DICT_VALUE.like(dictValue))
                .and(SYS_DICT.MODULE_NAME.like(moduleName))
                .and(SYS_DICT.TYPE.eq(type))
                .and(SYS_DICT.DICT_NAME.like(dictName)).orderBy(SYS_DICT.SORT.asc());

    }
//    @Override
//    public List<SysDict> listByKey(String key) {
//        List<SysDict> allDict = allDict();
//        return allDict.stream().filter(e -> e.getDictKey().equals(key)).toList();
//    }

    /**
     * 从缓存中获取字典数据
     */
    @Override
    public SysDict getDict(String dictKey) {
        Optional<SysDict> first = allDict().stream().filter(dict -> dict.getDictKey().equals(dictKey)).findFirst();
        return first.orElse(null);
    }

    @Override
    public String getString(String dictKey) {
        return this.getString(dictKey, null);
    }

    @Override
    public String getString(String dictKey, String defaultValue) {
        SysDict dict = getDict(dictKey);

        if (dict != null) return dict.getDictValue();

        return defaultValue;
    }

    @Override
    public int getInt(String dictKey) {
        String value = getString(dictKey);
        return Integer.parseInt(value);

    }

    @Override
    public int getInt(String dictKey, int defaultValue) {
        String value = getString(dictKey);

        if (StringKit.isBlank(value)) return defaultValue;

        return Integer.parseInt(value);
    }

    @Override
    public long getLong(String dictKey) {
        String value = getString(dictKey);
        return Long.parseLong(value);
    }

    @Override
    public long getLong(String dictKey, long defaultValue) {
        String value = getString(dictKey);

        if (StringKit.isBlank(value)) return defaultValue;

        return Long.parseLong(value);
    }

    @Override
    public JSONObject getJSONObject(String dictKey) {
        String value = getString(dictKey);

        return JSONObject.parseObject(value);
    }

    @Override
    public JSONObject getJSONObject(String dictKey, JSONObject defaultValue) {
        String value = getString(dictKey);
        if (StringKit.isBlank(value)) return defaultValue;
        return JSONObject.parseObject(value);
    }

    @Override
    public JSONArray getJSONArray(String dictKey) {
        String value = getString(dictKey);
        return JSONArray.parseArray(value);
    }

    @Override
    public JSONArray getJSONArray(String dictKey, JSONArray defaultValue) {
        String value = getString(dictKey);
        if (StringKit.isBlank(value)) return defaultValue;
        return JSONArray.parseArray(value);
    }

    @Override
    public <T> T getOne(String dictKey, Class<T> tClass) {
        String value = getString(dictKey);
        return JSONObject.parseObject(value, tClass);
    }

    @Override
    public <T> T getOne(String dictKey, Class<T> tClass, T defaultValue) {
        String value = getString(dictKey);
        if (StringKit.isBlank(value)) return defaultValue;
        return JSONObject.parseObject(value, tClass);
    }

    @Override
    public <T> List<T> getList(String dictKey, Class<T> tClass) {
        String value = getString(dictKey);
        return JSONArray.parseArray(value).toJavaList(tClass);
    }

    @Override
    public <T> List<T> getList(String dictKey, Class<T> tClass, List<T> defaultValue) {
        String value = getString(dictKey);
        if (StringKit.isBlank(value)) return defaultValue;
        return JSONArray.parseArray(value).toJavaList(tClass);
    }

}
